import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, ActionSheet, Toast } from "antd-mobile";
import dayjs from "dayjs"; // 导入 dayjs
import "./update.css";
import axios from "axios";

export default function Update_My() {
  // 获取form 表单元素
  const [form] = Form.useForm();

  // 用于页面跳转
  const navigate = useNavigate();

  // 控制性别选择的状态
  const [Two, setTwo] = useState(false);

  // 存储头像的URL
  const [imageUrl, setImageUrl] = useState(null);

  // 控制ActionSheet显示与隐藏
  const [visible, setVisible] = useState(false);

  // 控制拍照或选择相册逻辑
  const handleActionSheetClick = (index) => {
    if (index === 0) {
      // 调用拍照功能
      handleTakePhoto();
    } else if (index === 1) {
      // 打开文件选择框
      handleChooseFromGallery();
    }
    setVisible(false); // 关闭ActionSheet
  };

  // 打开相机拍照
  const handleTakePhoto = () => {
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
          // 创建一个video元素来显示摄像头画面
          const video = document.createElement("video");
          video.srcObject = stream;
          video.play();
          // 这里可以通过canvas或者直接从video中获取截图
          console.log("Camera opened for taking photo");
        })
        .catch((error) => {
          console.error("Error accessing the camera: ", error);
        });
    } else {
      console.log("Camera not supported in this browser");
    }
  };

  // 从相册中选择图片
  const handleChooseFromGallery = () => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";

    input.onchange = (e) => {
      const file = e.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onloadend = () => {
          // 获取图片的 Base64 路径
          const base64Url = reader.result;
          setImageUrl(base64Url); // 更新 imageUrl
          form.setFieldsValue({ image: base64Url }); // 更新表单中的 image 字段
        };
        reader.readAsDataURL(file); // 读取文件为 Base64 格式
      }
    };
    input.click();
  };

  // 表单提交函数
  const onFinish = async (values) => {
    try {
      const res = await axios.post("http://127.0.0.1:8000/switch_img", values);
      if (res.data.code === 200) {
        Toast.show({
          icon: "success",
          content: "保存成功",
        });

        navigate("/my"); // 跳转到 my 页面
      }
    } catch (error) {
      console.log("表单提交出现了错误" + error);
    }
  };

  // 用户的全部数据
  const [user, setuser] = useState(null);

  useEffect(() => {
    getUser();
  }, []);

  const getUser = async () => {
    try {
      const res = await axios.get("http://127.0.0.1:8000/loginInfo");
      console.log(res.data.data); // 确认返回的数据

      if (res.data.code === 200) {
        // 假设返回的是一个包含多个用户信息的数组
        setuser(res.data.data);
      }
    } catch (error) {
      console.log("我的..获取用户信息失败！" + error);
    }
  };

  const actions = [
    { text: "男", key: "男", onClick: () => handleSex(1) },
    { text: "女", key: "女", onClick: () => handleSex(0) },
  ];

  const handleSex = (num) => {
    if (num === 1) {
      form.setFieldsValue({ sex: "男" });
      setTwo(false);
    } else {
      form.setFieldsValue({ sex: "女" });
      setTwo(false);
    }
  };

  return (
    <div className="Update_My">
      {/* 页面顶部 */}
      <div className="update_title">
        <div className="update_title_left">
          <span onClick={() => navigate("/my")}>
            <svg
              t="1733148115622"
              className="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="4271"
              width="16"
              height="16"
            >
              <path
                d="M665.6 1011.2 716.8 972.8 345.6 512 716.8 51.2 665.6 12.8 262.4 512Z"
                fill="#272636"
                p-id="4272"
              ></path>
            </svg>
          </span>
        </div>
        <div className="update_title_right">编辑资料</div>
      </div>

      {/* 头像部分 */}
      <div className="update_load">
        <img
          src={imageUrl || user?.img_url} // 如果 imageUrl 为空则显示默认路径
          alt="头像"
          style={{ width: "100px", height: "100px", marginLeft: "150px" }}
        />
        <div style={{ marginTop: "10px" }}>
          <span
            style={{ marginLeft: "160px", fontSize: "12px", cursor: "pointer" }}
            onClick={() => setVisible(true)} // 显示ActionSheet
          >
            点击更换头像
          </span>
        </div>
      </div>

      {/* 表单部分 */}
      <Form
        name="form"
        onFinish={onFinish}
        form={form}
        initialValues={{
          name: "",
          sex: "",
          email: "",
          image: "",
        }}
        footer={
          <Button block type="submit" color="primary" size="large">
            提交
          </Button>
        }
      >
        {/* 用户名字段 */}
        <Form.Item name="name" label="用户名" rules={[{ required: true }]}>
          <Input placeholder="请输入姓名" />
        </Form.Item>

        {/* 性别字段 */}
        <Form.Item name="sex" label="性别" help="请选择性别">
          <Input readOnly onClick={() => setTwo(true)} />
        </Form.Item>

        {/* 邮箱字段 */}
        <Form.Item name="email" label="邮箱">
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        {/* 头像字段 */}
        <Form.Item name="image" label="头像" style={{ display: "none" }}>
          <Input />
        </Form.Item>
      </Form>

      {/* ActionSheet：用于区分男，女性别 */}
      <ActionSheet
        visible={Two}
        actions={actions}
        onClose={() => setTwo(false)}
      />
      {/* ActionSheet：用于选择拍照或从相册中选择 */}
      <ActionSheet
        visible={visible}
        actions={[
          { text: "拍照", onClick: () => handleActionSheetClick(0) },
          { text: "从相册中选择", onClick: () => handleActionSheetClick(1) },
        ]}
        cancelText="取消"
        onClose={() => setVisible(false)} // 关闭ActionSheet
      />
    </div>
  );
}
